import Util from './util';
let framework = undefined;
let mviews = {};
var wc = null,
  ws = null;


class MiniApp {
  constructor(fw) {
    framework = fw;
  }
  get user() {
    let cuser = vue.$f7.data.currentUser;
    return {
      userId: cuser.userId,
      userName: cuser.userName,
      loginId: cuser.loginId,
      address: cuser.profile.address,
      birthday: cuser.profile.birthday,
      email: cuser.profile.email,
      gender: cuser.profile.gender,
      mobile: cuser.profile.mobile
    }
  }

  isLogined() {
    if (this.user && this.user.loginId && this.user.userId) {
      return true;
    }
    return false;
  }

  // preloading() {
  //   Util.plusReady(() => {
  //     (window.vue.$store.state.miniApps || []).forEach(a => {
  //       if (a.preloading && (this.isLogined() || !a.isLogin)) {
  //         this.create(a.appCode, true);
  //       }
  //     });
  //   });
  // }

  getMiniToken(key) {
    let mapp = this.findOption(key);
    if (mapp) {
      return Util.encryptLongRSA(JSON.stringify({
        userId: this.user.userId,
        loginId: this.user.loginId,
        userName: this.user.userName,
        timestamp: new Date().getTime()
      }), mapp.publicKey);
    }
  }

  create(mapp, theme, callback) {
    let nWaiting = undefined;
    let miniToken = Util.encryptLongRSA(JSON.stringify({
      userId: this.user.userId,
      loginId: this.user.loginId,
      userName: this.user.userName,
      timestamp: new Date().getTime()
    }), mapp.publicKey);
    if (window.ipcRenderer) {
      // 导入小程序
      mapp.miniToken = miniToken;
      window.ipcRenderer.send('importMiniApps', {
        miniApp: mapp,
        user: this.user,
      });
      return mapp;
    } else {
      // 创建窗口create
      let styles = {}
      if(plus.device.vendor === 'Apple'){
        styles = {
          additionalHttpHeaders: [{
            "mini-token": miniToken
          }]
        }
      }else{
        styles = {
          // ios不支持render属性
          titleNView: false,
          render: 'always',
          additionalHttpHeaders: [{
            "mini-token": miniToken
          }]
          //plusrequire: "ahead",
        };
      }

      if (mapp.isTitleBar) {
        styles.titleNView = {
          autoBackButton: false,
          //homeButton: true,
          titleText: mapp.appName,
          backgroundColor: theme == 'blue' ? '#244fa1' : "#3096ef",
          titleColor: "#fff",
          progress: {
            color: "rgba(119,136,153,0.5)",
            height: "5px"
          },
          render: "always"
        };
      }
      var mview = plus.webview.create(mapp.appLink, mapp.appCode, styles, {
        user: this.user,
        miniToken: miniToken,
        preloading: mapp.preloading,
        appCode: mapp.appCode,
      });
      // mview.setPullToRefresh({
      //   support: true
      // }, () => {
      //   mview.endPullToRefresh();
      //   mview.reload();
      // });
      // 创建侧边栏
      wc = plus.webview.create('_www/static/sidebar/miniapp.html', "侧边栏", {
        left: '0%',
        width: '70%',
        popGesture: 'none',
        scrollIndicator: 'none',
        scalable: false,
        backButtonAutoControl: 'close',
      }, {
        // information: vue.$framework.account.getMiniappHomePage()
      });
      // mview.evalJS("window.miniApp = { } "
      mview.appendJsFile("_www/static/libs/qmsdk.js");
      if (mapp.cssText) {
        mview.setCssText(mapp.cssText);
      }
      // listenResourceLoading监听页面开始加载资源
      mview.listenResourceLoading({
        match: ".*"
      }, e => {
        if (mapp.listenResourceJs) {
          mview.evalJS(mapp.listenResourceJs);
        }
        mview.canBack(function (e) {
          let titleNView = mview.getTitleNView();
          if (titleNView && titleNView.isVisible()) {
            if (e.canBack) {
              mview.setStyle({
                titleNView: {
                  autoBackButton: true
                }
              });
            } else {
              mview.setStyle({
                titleNView: {
                  autoBackButton: false
                }
              });
            }
          }
        });
      });

      mview.overrideResourceRequest([{
        match: '.*um-sdk.*',
        redirect: '_www/static/libs/umsdk.js'
      }]);
      mview.loadURL(mapp.appLink);
      // addEventListener添加事件监听器

      // 窗口开始渲染时事件
      mview.addEventListener("rendering", (e) => {})
      // 窗口开始加载事件
      mview.addEventListener('loading', (e) => {
        // let titleNView = mview.getTitleNView();
        // if (titleNView && titleNView.isVisible()) {
        //   titleNView.drawRichText('<img src="_www/static/img/btn/app-r.png" style="width: 50px;height: 35px;"/>', {
        //     right: '0px',
        //     width: '50px',
        //     top: '5px'
        //   }, {
        //     onClick: function (r) {
        //       if (mapp.preloading) {
        //         mview.hide("slide-out-bottom");
        //         wc.close("auto");
        //         wc = null
        //       } else {
        //         mview.close("slide-out-bottom");
        //         wc.close("auto");
        //         wc = null
        //       }
        //     }
        //   }, "app-r");

        //   titleNView.drawRichText('<img src="_www/static/img/btn/app-l.png" style="width: 50px;height: 35px;"/>', {
        //     right: '50px',
        //     width: '50px',
        //     top: '5px'
        //   }, {
        //     onClick: function (r) {
        //       plus.nativeUI.actionSheet({
        //           title: mapp.appName,
        //           cancel: "退出",
        //           buttons: [
        //             // { title: "添加到桌面" },
        //             {
        //               title: "刷新"
        //             }
        //           ]
        //         },
        //         function (e) {
        //           switch (e.index) {
        //             case 0:
        //               if (mapp.preloading) {
        //                 mview.hide("slide-out-bottom");
        //               } else {
        //                 mview.close("slide-out-bottom");
        //               }
        //               break;
        //               // case 1:
        //               //     plus.navigator.createShortcut({
        //               //         name: mapp.appName,
        //               //         toast: mapp.appName + "已创建桌面快捷方式",
        //               //         icon: "_www/static/img/icon/ent_icon1.png",
        //               //         extra: {
        //               //             miniApp: mapp.appCode
        //               //         }
        //               //     }, (r) => {
        //               //         if (!r.sure) {
        //               //             vue.$f7.dialog.alert("创建失败");
        //               //         }
        //               //     });
        //               //     break;
        //             case 1:
        //               //header无法带过去
        //               //mview.reload(true);
        //               mview.loadURL(mapp.appLink, {
        //                 "mini-token": miniToken
        //               });
        //               nWaiting = plus.nativeUI.showWaiting("正在加载中");
        //               break;
        //           }
        //         }
        //       );
        //     }
        //   }, "app-l");
        //   titleNView.drawRichText('<img src="_www/static/img/btn/app-2.png" style="width: 50px;height: 35px;"/>', {
        //     left: "0px",
        //     width: '50px',
        //     top: '5px'
        //   }, {
        //     onClick: function (r) {
        //       // 点击获取数据
        //       wc.evalJS("miniapp.getuser('" + key + "')")
        //       // 开启遮罩
        //       mview.setStyle({
        //         mask: 'rgba(0,0,0,0.5)'
        //       });
        //       wc.show('slide-in-left', 200);
        //       // 侧滑页面关闭后关闭遮罩
        //       wc.addEventListener('hide', function () {
        //         mview.setStyle({
        //           mask: 'none'
        //         });
        //       }, false);
        //       if (window.plus) {
        //         plusReady();
        //       } else {
        //         document.addEventListener('plusready', plusReady, false);
        //       }

        //       function plusReady() {
        //         // 用户点击遮罩层后
        //         mview.addEventListener('maskClick', function () {
        //           wc.hide("slide-out-left", 200);
        //         }, false);
        //       }
        //     }
        //   }, "app-2")
        // }
      }, false);
      // 窗口加载完成事件
      mview.addEventListener("loaded", () => {
        if (nWaiting) {
          nWaiting.close();
        }
        if (mapp.backJS) {
          mview.evalJS(mapp.backJS);
        }
        if (callback && callback.loaded) {
          callback.loaded();
        }
      }, false);
      // 窗口关闭事件
      mview.addEventListener('close', () => {
        if (mviews[mapp.appCode]) {
          mviews[mapp.appCode] = undefined;
        }
      }, false);

      if (mapp.preloading) {
        mviews[mapp.appCode] = mview;
      }
      return mview;
    }
  }

  open(key, callback, theme) {
    let mapp = _.isObject(key) ? key : this.findOption(key);
    if(window.electron){
      window.electron.ipcRenderer.send("lc-message",mapp);
    }

    if (mapp) {
      let mview = null;
      if (mapp.preloading && mviews[mapp.appCode] != undefined) {
        mview = mviews[mapp.appCode];
        mview.show("slide-in-bottom");
      } else {
        let nWaiting = plus.nativeUI.showWaiting("正在加载中");
        mview = this.create(mapp, theme, {
          loaded: () => {
            window.setTimeout(() => {
              nWaiting.close();
              mview.show("slide-in-bottom");
            }, 500);
          }
        });
      }
      if (window.ipcRenderer) {
        // 发送消息，那边会显示已创建好的窗口
        window.ipcRenderer.send("openMiniApp", {
          miniApp: mapp,
        });
      }
      wc = plus.webview.create('_www/static/sidebar/miniapp.html', "test", {
        left: '0%',
        width: '70%',
        popGesture: 'none',
        scrollIndicator: 'none',
        scalable: false,
        backButtonAutoControl: 'close',
      }, {
        // information: vue.$framework.account.getMiniappHomePage()
      });
      // mview.evalJS(
      //   "window.miniApp.switchSkin('" + theme + "')"
      // );
    } else {
      this.$f7.dialog.alert("小程序配置不存在，请联系管理员");
      if (callback) {
        callback({
          sucess: false,
          message: "小程序配置不存在，请联系管理员"
        });
      }
    }
  }

  findOption(key) {
    return Util.findLast(window.vue.$store.state.miniApps, (a) => {
      return a.appCode == key;
    });
  }
  getToken(publicKey) {
    return Util.encryptLongRSA(JSON.stringify({
      userId: this.user.userId,
      loginId: this.user.loginId,
      userName: this.user.userName,
      timestamp: new Date().getTime()
    }), publicKey);
  }
}


export default new  MiniApp();
